<script setup>
import * as API from '@/api/deal/deal-voucher.js'
import {reqCascaderData} from '@/api/deal/deal-product.js'
import {ref, reactive, onMounted} from 'vue'
import {getLocalTime} from "@/utils/time.js";
import {ElMessage} from "element-plus";
import {reqListVoucher} from "@/api/item/voucher.js";

// 用于表格
const pn = ref(1)
const ps = ref(10)
const total = ref(0)
const couponList = ref([])
const couponStatus = ref([
  {label:"已分发", value:0, type:"primary"},
  {label:"已使用", value:1, type:"info"},
])



const searchOption = reactive({
  multistageOptions: {
    storeId: null,
    clerkId: null,
    customerId: null,
  },
  couponId: null,
  timeRange: [null, null],
  type: null,
})

const handleTimeRangeChange = (value) => {
  if (!value) {
    searchOption.timeRange = [null, null]; // 确保在清空时，数组也完全重置
  }
}

const clearTimeRange = () => {
  searchOption.timeRange = [null, null]; // 在用户手动清空时重置
}
// 级联选择器 搜索 | 表单项
const optionTreeValue = ref([])
const optionsTree = ref([])
const couponTypeList = ref([])
const optionTreeHandler = (value)=>{
  if (!value || value.length === 0) {
    // 当级联选择器清空时，将 multistageOptions 的所有属性清空
    searchOption.multistageOptions.storeId = null;
    searchOption.multistageOptions.clerkId = null;
    searchOption.multistageOptions.customerId = null;
  } else {
    // 正常处理级联选择器的选中值
    searchOption.multistageOptions.storeId = value[0] || null;
    searchOption.multistageOptions.clerkId = value[1] || null;
    searchOption.multistageOptions.customerId = value[2] || null;
  }
}

const optionTreeValueForm = ref([])
const optionTreeFormHandler = (value)=>{
  if (!value || value.length === 0) {
    // 当级联选择器清空时，将 multistageOptions 的所有属性清空
    couponParams.storeId = null
    couponParams.clerkId = null
    couponParams.customerId = null
  } else {
    couponParams.storeId = value[0] || null
    couponParams.clerkId = value[1] || null
    couponParams.customerId = value[2] || null
  }
}
//用于表单
const dialogFormVisible = ref(false)

const couponParams = reactive({
  id: null,
  storeId: null,
  clerkId: null,
  customerId: null,
  voucherId: null,
  dealTime: null,
  serial: null,
  type: null,
  notes: null,
})

const getPage = async (pager = 1)=>{
  pn.value = pager
  const result = await API.reqPage(
      pn.value,
      ps.value,
      searchOption.multistageOptions.storeId,
      searchOption.multistageOptions.clerkId,
      searchOption.multistageOptions.customerId,
      searchOption.couponId,
      searchOption.timeRange[0],
      searchOption.timeRange[1],
      searchOption.type,
  )
  if(result.code === "0"){
    total.value = result.data.total
    couponList.value = result.data.items
    console.log(couponList.value)
  } else {
    ElMessage({type:"error", message:"获取数据失败！"})
  }
}

// const reqExport = async () => {
//   try {
//     const resp = await API.reqExport();
//     if (resp != null) {
//       ElMessage({
//         message: '导出成功',
//         type: 'success',
//       });
//       const link = document.createElement('a');
//       link.href = URL.createObjectURL(resp);
//       link.download = 'data.xlsx';
//       link.click();
//       URL.revokeObjectURL(link.href);
//     }
//   } catch (error) {
//     ElMessage({
//       message: '导出失败',
//       type: 'error',
//     });
//   }
// };

const addCoupon = ()=>{
  dialogFormVisible.value = true
  Object.assign(couponParams,{
    id: null,
    storeId: null,
    clerkId: null,
    customerId: null,
    voucherId: null,
    dealTime: null,
    serial: null,
    type: null,
    notes: null,
  })
  optionTreeValueForm.value = [null, null, null]
}

const updateCoupon = (row)=>{
  dialogFormVisible.value = true
  Object.assign(couponParams,row)
  optionTreeValueForm.value = [
      couponParams.storeId,
      couponParams.clerkId,
      couponParams.customerId,
  ]
}

const deleteCoupon = async (id)=>{
  const result = await API.reqDelete(id)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功' })
    await getPage(couponList.value.length > 1 ? pn.value : pn.value - 1);
  }
}

const cancel = ()=>{
  dialogFormVisible.value = false
}

const confirm = async ()=>{
  let result
  if(couponParams.id){
    result = await API.reqUpdate(couponParams)
  }else{
    result = await API.reqSave(couponParams)
  }
  if (result.code === '0') {
    ElMessage({ type: 'success', message: couponParams.id? '修改成功':'添加成功',})
    dialogFormVisible.value = false
    await getPage()
  } else {
    dialogFormVisible.value = false
    //提示消息
    ElMessage({ type: 'error', message: couponParams.id ? '修改失败':'添加失败' });
  }
}

const search = async ()=>{
  await getPage()
}

onMounted(()=>{
  //获取级联树
  reqCascaderData().then(resp => {
    optionsTree.value = resp.data.nameIdList
  })
  //获取卡券类型列表
  reqListVoucher().then(resp=>{
    couponTypeList.value = resp.data.items
  })
  getPage()
})
</script>

<template>
  <!-- ----------------------------------- search ----------------------------------- -->
  <el-card>
    <el-scrollbar>
      <el-form class="search-card">
        <div class="search-input">
          <el-cascader
              placeholder="客户名"
              v-model="optionTreeValue"
              :options="optionsTree"
              @change="optionTreeHandler"
              expandTrigger="hover"
              :props="{ value: 'id', label: 'name', children: 'childrenList', checkStrictly: true, }"
              clearable
              filterable
          />
          <el-form-item label="卡券名">
            <el-select v-model="searchOption.couponId" clearable placeholder="卡券名" style="width:180px">
              <el-option
                  v-for="item in couponTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
                v-model="searchOption.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleTimeRangeChange"
                @clear="clearTimeRange"
            />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="searchOption.type" clearable placeholder="交易状态" style="width:180px">
              <el-option
                  v-for="item in couponStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" size="default" @click="search" >搜索</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!-- ----------------------------------- search ----------------------------------- -->

  <!-- ----------------------------------- table ----------------------------------- -->
  <el-card>
    <el-button type="primary" size="default" @click="addCoupon">添加</el-button>
    <!-- <el-button type="primary" size="default" @click="reqExport">导出</el-button> -->

    <el-table  style="margin: 10px 0;" border :data="couponList">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="订单编号" align="center" prop="id" show-overflow-tooltip></el-table-column>
      <el-table-column label="分店名" align="center" prop="storeName" show-overflow-tooltip></el-table-column>
      <el-table-column label="店员名" align="center" prop="clerkName" show-overflow-tooltip></el-table-column>
      <el-table-column label="客户名" align="center" prop="customerName" show-overflow-tooltip></el-table-column>
      <el-table-column label="卡券名" align="center" prop="voucherName" show-overflow-tooltip></el-table-column>
      <el-table-column label="交易时间" align="center" prop="dealTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.dealTime, 1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="卡券编号" align="center" prop="serial" show-overflow-tooltip></el-table-column>
      <el-table-column label="类型" align="center" prop="type" show-overflow-tooltip>
        <template #default="{row}">
          <el-tag :type="couponStatus[row.type].type">{{ couponStatus[row.type].label }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用订单编号" align="center" prop="dealProductId" show-overflow-tooltip></el-table-column>
      <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建/修改时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.createTime)}}</span>
          <br/>
          <span>{{getLocalTime(row.updateTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{row, $index}">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="updateCoupon(row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`确定要删除?`" width="260px" @confirm="deleteCoupon(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="(size) => { ps.value = size; getPage(); }"
        @current-change="getPage"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>
  <!-- ----------------------------------- table ----------------------------------- -->

  <!-- ----------------------------------- dialog ----------------------------------- -->
  <el-dialog
      v-model="dialogFormVisible"
      :title="couponParams.id ? '修改卡券' : '添加卡券'"
  >
    <el-form style="width: 80%" :model="couponParams">
      <el-form-item label="客户名" label-width="100px">
        <el-cascader
            placeholder="客户名"
            v-model="optionTreeValueForm"
            :options="optionsTree"
            @change="optionTreeFormHandler"
            expandTrigger="hover"
            :props="{ value: 'id', label: 'name', children: 'childrenList', }"
            clearable
            filterable
        />
      </el-form-item>
      <el-form-item label="卡券类型"  label-width="100px">
        <el-select v-model="couponParams.voucherId" clearable placeholder="卡券名" style="width:180px">
          <el-option
              v-for="item in couponTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易时间"  label-width="100px">
        <el-date-picker
            v-model="couponParams.dealTime"
            type="date"
            placeholder="交易时间"
        />
      </el-form-item>
      <el-form-item label="卡券编号"  label-width="100px">
        <p>（2 位大写字母 + 4 位数字编号，如 DY0001）</p>
        <el-input v-model="couponParams.serial"></el-input>
      </el-form-item>
      <el-form-item label="类型"  label-width="100px">
        <el-select v-model="couponParams.type" clearable placeholder="类型" style="width:180px">
          <el-option
              v-for="item in couponStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注"  label-width="100px">
        <el-input v-model="couponParams.notes" type="textarea"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- ----------------------------------- dialog ----------------------------------- -->
</template>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  margin-bottom: 1rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
  gap: 1rem;
}
.search-input > * {
  flex: 0 1 auto;
}
.el-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}
.el-form-item label {
  width: 80px; /* Adjust this value as needed */
}
.el-card {
  margin-bottom: 1rem;
}
.el-table {
  margin: 1rem 0;
}
.el-dialog {
  width: 50%;
}
.el-dialog .el-form-item {
  margin-bottom: 1rem;
}
.el-dialog .el-form-item p {
  margin-bottom: 0.5rem;
}
</style>
